package com.hh.us.service.impl;

import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.UrlValidator;
import org.springframework.stereotype.Service;

import sun.misc.BASE64Encoder;

import com.google.common.hash.Hashing;
import com.hh.us.dao.IUrlsDao;
import com.hh.us.entity.Urls;
import com.hh.us.service.IUrlsService;

@Service
public class UrlsService implements IUrlsService {
	private static final Random RANDOM = new SecureRandom();

	@Resource
	private IUrlsDao urlDao;

	@Override
	public Urls findBySurl(String surl) {
		return urlDao.findOneByProperty("surl", surl);
	}

	@Override
	public Urls shortUrl(Urls urls) {
		if (urls != null && StringUtils.isNotBlank(urls.getLurl())) {
			String url = StringUtils.trimToEmpty(urls.getLurl());
			UrlValidator urlValidator = new UrlValidator(new String[] { "http", "https" });
			if (urlValidator.isValid(url)) {
				Urls us = urlDao.findOneByProperty("lurl", url);
				if(us != null) {
					return us;
				}
				Date now = new Date();
				String salt = generateSalt();
				String surl = Hashing.murmur3_32().hashString(salt + url, Charsets.UTF_8).toString();
				us = new Urls(UUID.randomUUID().toString(), url, surl);
				us.setSalt(salt);
				us.setCreateDate(now);
				us.setUpdateDate(now);
				try {
					urlDao.create(us);
				} catch (Exception e) {//前一次查询后，插入前，有可能会出现被别人插入了重复数据而报错；
					return findBySurl(surl);
				}
				return us;
			}
		}
		return null;
	}

	private String generateSalt() {
		byte[] salt = new byte[8];
		RANDOM.nextBytes(salt);
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(salt);
	}

}
